package com.fwzc.giuseppe.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 工具类
 * @author suligen
 *
 */

public class PhoneHelper {

	/**
	 * 获取底部 navigation bar 高度
	 * 
	 * @param context
	 * @return
	 */
	@SuppressLint("NewApi")
	public static int getNavigationBarHeight(Context context) {    
		int height ;
		try {
			Resources resources = context.getResources();    
			int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");    
			height = resources.getDimensionPixelSize(resourceId);    
			
		} catch (Exception e) {
			// TODO: handle exception
			height=0;
		}
//		Log.v("dbw", "Navi height:" + height);    
		return height;
	}
	
	/**
	 * 获取顶部status bar 高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusBarHeight(Context context) {    
		Resources resources = context.getResources();    
		int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");    
		int height = resources.getDimensionPixelSize(resourceId);    
//		Log.v("dbw", "Status height:" + height);    
		return height;
	}
	
	/**
	 * 获取屏幕宽度
	 * 
	 * @param context
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static int getScreenWidth(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getWidth();
	}

	/**
	 * 获取屏幕高度
	 * 
	 * @param context
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static int getScreenHeight(Context context) {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		return display.getHeight();
	}

	
	/**
	 * 获取本地版本号
	 * @param context
	 * @return
	 */
	public static String getVersionCode(Context context) {
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packInfo =packageManager.getPackageInfo(context.getPackageName(), 0);
			String version = packInfo.versionName;
			return version;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "0.00";
		}
	}
	
	/**
	 * 
	 * 获取设备硬件信息
	 * 
	 * @return
	 */
	public static String mobileInformation(Context context){
		
		String st=PhoneHelper.IEMI(context)+"|"+PhoneHelper.OS()+"|"+PhoneHelper.systemVersion();
		
		return st;
	}
	
	
	/**
	 * 获取包名
	 * @param context
	 * @return
	 */
	public static String getPackageName(Context context){
		PackageManager pm = context.getPackageManager(); // 获得PackageManager对象  
		
		PackageInfo info = null;
		try {
			info = pm.getPackageInfo(context.getPackageName(), 0);
			String packageNames = info.packageName;   
			return packageNames;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "com.trj.platform.app.cn";
		}    
	}
	
	
	public static boolean sdCardExist(){
		
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
			return true;
			
		}else{
			return false;
		}
	}
	
	/** 保存png */
	public static void saveBitmap(String file,String picName,Bitmap bitmap) {
		
		File f = new File(file, picName);
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
//			System.out.println(e+"");
			e.printStackTrace();
		} catch (IOException e) {
//			System.out.println(e+"");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	public static String savePath(){
		File sdDir = null;
		if(sdCardExist()){
			sdDir = Environment.getExternalStorageDirectory();//获取跟目录
			
			return sdDir.toString();
		}else{
			return Environment.getDataDirectory().getPath();
		}
		
		
	}
	
	/**
	 * 获取系统唯一识别码
	 * @param context
	 * @return
	 */
	public static String IEMI(Context context){
		
		TelephonyManager mTelephonyMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = mTelephonyMgr.getDeviceId();
		return imei;
		
	}
	
	/**
	 * 获取系统操作系统
	 * @param context
	 * @return
	 */
	public static String OS(){
		String os = Build.MODEL;
		return os;
	}
	
	/**
	 * 获取系统版本号
	 * @param context
	 * @return
	 */
	public static String systemVersion(){
		String version = Build.VERSION.RELEASE;
		return version;
	}

	/**
	 * 获取手机像素高宽
	 */
	public static DisplayMetrics getWindowPx(Activity act) {
		DisplayMetrics metric = new DisplayMetrics();
		act.getWindowManager().getDefaultDisplay().getMetrics(metric);
		return metric;
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	  /**
     * sp转px.
     *
     * @param value   the value
     * @param context the context
     * @return the int
     */
    public static int sp2px(float value, Context context) {
        Resources r;
        if (context == null) {
            r = Resources.getSystem();
        } else {
            r = context.getResources();
        }
        float spvalue = value * r.getDisplayMetrics().scaledDensity;
        return (int) (spvalue + 0.5f);
    }


    /**
     * px转sp.
     *
     * @param value   the value
     * @param context the context
     * @return the int
     */
    public static int px2sp(float value, Context context) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (value / scale + 0.5f);
    }

	
	/**
	 * 获取手机网络状态
	 */
	public static int getNetWorkState(Context context) {
		ConnectivityManager connectMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = connectMgr.getActiveNetworkInfo();
		return netInfo == null ? ConnectivityManager.TYPE_WIFI : netInfo
				.getType();
	}

	/**
	 * 手机网络是否连接;
	 * 
	 * @param context
	 * @return false 未联网
	 */
	public static boolean getNetActiveState(Context context) {
		ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = connectMgr.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnected()) {
			return netInfo.isAvailable();
		}
		return false;
	}

	public static void showxInputSoft(View v) {
		InputMethodManager inputManager = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		inputManager.showSoftInput(v, 0);
	}

	public static void hideInputSoft(View v) {
		InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
	}

	public static void hideInputSoft(Context context, IBinder token) {
		if (token != null) {
			InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
			im.hideSoftInputFromWindow(token,InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}
	
	/**
     * 清除本应用内部缓存(/data/data/com.xxx.xxx/cache)
     * 
     * @param context
     */
    public static void cleanInternalCache(Context context) {
        deleteFilesByDirectory(context.getCacheDir());
    }

    /**
     * 清除本应用所有数据库(/data/data/com.xxx.xxx/databases)
     * 
     * @param context
     */
    public static void cleanDatabases(Context context) {
        deleteFilesByDirectory(new File("/data/data/" + context.getPackageName() + "/databases"));
    }

    /**
     * 清除本应用SharedPreference(/data/data/com.xxx.xxx/shared_prefs)
     * 
     * @param context
     */
    @SuppressLint("SdCardPath") 
    public static void cleanSharedPreference(Context context) {
        deleteFilesByDirectory(new File("/data/data/"+ context.getPackageName() + "/shared_prefs"));
    }

    /**
     * 按名字清除本应用数据库
     * 
     * @param context
     * @param dbName
     */
    public static void cleanDatabaseByName(Context context, String dbName) {
        context.deleteDatabase(dbName);
    }

    /**
     * 清除/data/data/com.xxx.xxx/files下的内容
     * 
     * @param context
     */
    public static void cleanFiles(Context context) {
        deleteFilesByDirectory(context.getFilesDir());
    }

    /**
     * 清除外部cache下的内容(/mnt/sdcard/android/data/com.xxx.xxx/cache)
     * 
     * @param context
     */
    public static void cleanExternalCache(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteFilesByDirectory(context.getExternalCacheDir());
        }
    }

    /**
     * 清除自定义路径下的文件，使用需小心，请不要误删。而且只支持目录下的文件删除
     * 
     * @param filePath
     */
    public static void cleanCustomCache(String filePath) {
        deleteFilesByDirectory(new File(filePath));
    }

    /**
     * 清除本应用所有的数据
     * 
     * @param context
     * @param filepath
     */
    public static void cleanApplicationData(Context context, String... filepath) {
        cleanInternalCache(context);
        cleanExternalCache(context);
        cleanDatabases(context);
        cleanSharedPreference(context);
        cleanFiles(context);
        for (String filePath : filepath) {
            cleanCustomCache(filePath);
        }
    }
    
    /**
     * 删除方法 这里只会删除某个文件夹下的文件，如果传入的directory是个文件，将不做处理
     * 
     * @param directory
     */
    private static void deleteFilesByDirectory(File directory) {
        if (directory != null && directory.exists() && directory.isDirectory()) {
            for (File item : directory.listFiles()) {
                item.delete();
            }
        }
    }
	
 
	/**
	 * 光标移至最后
	 * @param ed_content EditText
	 */
	public static void moveCursor(EditText ed_content) {
		Editable editable = ed_content.getText();
		ed_content.setSelection(editable.length());
	}
	
	
	/**
	 * 动态设置listview高度,并控制最高高度
	 * @param context
	 * @param listView
	 */
	public static void setListViewHeightBasedOnChildren(Context context,ListView listView,int height) {
		
		 //获取listview的适配器
	    ListAdapter listAdapter = listView.getAdapter();
	    //item的高度
	    int itemHeight = 46;

	    if (listAdapter == null) {
	        return;
	    }

	    int totalHeight = 0;

	    for (int i = 0; i < listAdapter.getCount(); i++) {
	    	
	    	if(totalHeight<PhoneHelper.dip2px(context,height)){
	    		totalHeight += PhoneHelper.dip2px(context,itemHeight)+listView.getDividerHeight();
	    	}
	    }

	    ViewGroup.LayoutParams params = listView.getLayoutParams();
	    params.height = totalHeight;

	    listView.setLayoutParams(params);
	}
}
